package com.mycharx.springboothibernate.dao.impl;

import com.mycharx.springboothibernate.dao.SsoUserDao;
import com.mycharx.springboothibernate.entity.SsoUser;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;

/**
 * The type Sso user dao.
 *
 * @author 张卜亢
 * @date 2020.03.27 23:04:34
 */
@Repository("ssoUserDao")
public class SsoUserDaoImpl implements SsoUserDao {

    @Resource
    private HibernateTemplate hibernateTemplate;

    @Override
    public List<SsoUser> findAll() {
        return hibernateTemplate.loadAll(SsoUser.class);
    }

    @Override
    public Page<SsoUser> findAllPage(final Pageable pageable) {
        final String hql = "from SsoUser";
        return hibernateTemplate.execute(session -> {
            long count = session.createQuery("select count(1) " + hql, Long.class).uniqueResult();
            List<SsoUser> ssoUserList = session.createQuery(hql, SsoUser.class)
                    .getResultList();
            return new PageImpl<>(ssoUserList, pageable, count);
        });
    }

    @Override
    public SsoUser saveOrUpdate(SsoUser ssoUser) {
        hibernateTemplate.saveOrUpdate(ssoUser);
        return ssoUser;
    }
}
